package com.ruoyi.locksApi.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.lock.config.LockApiConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 定时获取apartmentLogin token并存入Redis
 */
@Slf4j
@Component
public class ApartmentTokenTask {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private LockApiConfig lockApiConfig;

    public static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : messageDigest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 定时执行，实际刷新频率可根据expireTime动态调整
    @Scheduled(fixedDelayString = "${lock.api.schedule.refresh-interval:300000}")
    public void refreshToken() {
        try {
            // 构造请求体
            Map<String, Object> data = new HashMap<>();
            data.put("accountName", lockApiConfig.getAccount());
            data.put("password", md5(lockApiConfig.getPassword()));
            Map<String, Object> req = new HashMap<>();
            req.put("method", "apartmentLogin");
            req.put("data", data);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.valueOf("text/json;charset=utf-8"));
            headers.add("Content-Version", "1.0");
            HttpEntity<String> entity = new HttpEntity<>(JSONObject.toJSONString(req), headers);

            String respStr = restTemplate.postForObject(lockApiConfig.getLoginUrl(), entity, String.class);
            JSONObject resp = JSONObject.parseObject(respStr);
            if (resp != null && resp.getIntValue("resultCode") == 0) {
                JSONObject respData = resp.getJSONObject("data");
                String token = respData.getString("tokenId");
                int expire = respData.getIntValue("expireTime");
                // 提前刷新时间
                int expireSeconds = Math.max(expire - lockApiConfig.getSchedule().getAdvanceRefreshSeconds(), 
                                           lockApiConfig.getSchedule().getAdvanceRefreshSeconds());
                redisCache.setCacheObject(lockApiConfig.getRedisKey(), token, expireSeconds, TimeUnit.SECONDS);
                log.info("apartment token刷新成功，有效期:{}秒", expireSeconds);
            } else {
                log.error("apartmentLogin接口调用失败: {}", respStr);
            }
        } catch (Exception e) {
            log.error("apartment token刷新异常", e);
        }
    }
} 